package edu.biwu.request;/**
 * @author 王俊彪
 * @version 1.0
 */

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.UUID;
import java.util.stream.Collectors;

//处理多文件上传
@WebServlet("/req/upload02")
@MultipartConfig
public class ReqUploadDemo02 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        Collection<Part> uploadFiles = request.getParts();
        for (Part uploadFile : uploadFiles) {
            String fileName = uploadFile.getSubmittedFileName();
            //保证照片名称唯一
            String extension = fileName.substring(fileName.lastIndexOf("."));
            String newFileName=UUID.randomUUID()+extension;
            //服务器存储的位置
            File dir = new File("D://uploadFile");
            if(!dir.exists()){//如果文件不存在就创建文件夹
                dir.mkdir();
            }
            //通过路径直接上传到指定位置，底层已经把io流，编码封装好了
            uploadFile.write(dir+"/"+newFileName);
        }
        //上传成功后，响应上传成功提示
        String fileNames = uploadFiles.stream().map(uploadFile -> uploadFile.getSubmittedFileName())
                .collect(Collectors.joining(" , "));
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().write(fileNames+"上传成功");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
